package main

import (
	"mypassword/assets"
	"mypassword/middleware"
	_ "mypassword/routers"
	"mypassword/utils"
	"os"
	"path/filepath"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/filter/cors"
	_ "github.com/mattn/go-sqlite3"
)

func init() {
	// 恢复静态文件
	tempDir := filepath.Join(os.TempDir(), "mypassword-static")
	if err := assets.RestoreAssets(tempDir, ""); err != nil {
		panic(err)
	}

	// 注册数据库
	dbPath, _ := web.AppConfig.String("dbpath")
	err := orm.RegisterDriver("sqlite3", orm.DRSqlite)
	if err != nil {
		panic(err)
	}

	err = orm.RegisterDataBase("default", "sqlite3", dbPath)
	if err != nil {
		panic(err)
	}

	// 自动建表
	err = orm.RunSyncdb("default", false, true)
	if err != nil {
		panic(err)
	}

	// 加载RSA密钥对
	rsaUtil := utils.NewRSAUtil()
	if err := rsaUtil.LoadKeyPair(); err != nil {
		// 如果是首次运行，密钥对不存在是正常的
		if !os.IsNotExist(err) {
			panic(err)
		}
	}

	// 配置session
	web.BConfig.WebConfig.Session.SessionOn = true
	web.BConfig.WebConfig.Session.SessionName = "mypassword_session"
	web.BConfig.WebConfig.Session.SessionGCMaxLifetime = 3600
	web.BConfig.WebConfig.Session.SessionCookieLifeTime = 3600
	web.BConfig.WebConfig.Session.SessionAutoSetCookie = true
	web.BConfig.WebConfig.Session.SessionDomain = "localhost"
	web.BConfig.CopyRequestBody = true
}

func main() {
	// 添加中间件，排除静态文件
	web.InsertFilter("/api/*", web.BeforeRouter, middleware.AuthMiddleware)

	// 添加CORS中间件
	web.InsertFilter("*", web.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"},
		AllowHeaders:    []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "X-Requested-With"},
		ExposeHeaders:   []string{"Content-Length", "Access-Control-Allow-Origin"},
		MaxAge:          86400,
	}))

	// 设置静态文件目录为临时目录
	tempDir := filepath.Join(os.TempDir(), "mypassword-static")
	web.SetStaticPath("/", tempDir)
	web.SetStaticPath("/assets", filepath.Join(tempDir, "assets"))

	web.Run()
}
